package com.senyint.hip.fhir.web;

import ca.uhn.fhir.model.primitive.IdDt;
import ca.uhn.fhir.rest.api.MethodOutcome;
import ca.uhn.fhir.rest.client.impl.GenericClient;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.senyint.hip.fhir.interceptor.CaptureInterceptor;

import org.hl7.fhir.exceptions.FHIRException;
import org.hl7.fhir.r4.model.*;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * *******description*******
 * 医嘱
 * *************************
 *
 * @author ChenPan
 * @date 2019/7/1 14:25
 */
@RestController
@RequestMapping("/medication")
public class MedicationRequestController extends FhirBaseController {

    @PostMapping()
    public String createMedication(@RequestBody String data) {
        MedicationRequest request = convertMedication(data);

        CaptureInterceptor interceptor = new CaptureInterceptor();
        GenericClient client = newClient(tempData.getBaseServer(), interceptor);

        MethodOutcome out = client.create().resource(request).execute();

        return new Gson().toJson(out);

    }

    @PutMapping("/{id}")
    public String updateMedication(@PathVariable("id") String id, @RequestBody String data) throws FHIRException {
        MedicationRequest request = convertMedication(data);

        CaptureInterceptor interceptor = new CaptureInterceptor();
        GenericClient client = newClient(tempData.getBaseServer(), interceptor);

        MethodOutcome out = client.update(id, request);

        return new Gson().toJson(out);

    }

    protected MedicationRequest convertMedication(String data) {
        JSONObject jsonObject = JSON.parseObject(data);

        MedicationRequest request = new MedicationRequest();
        Medication medication = new Medication();

        medication.setId(new IdDt("#" + jsonObject.getString("drugCode")));
        //药品属性  医保药品编码，名称
        medication.setCode(new CodeableConcept()
                .addCoding(new Coding("http://www.nhsa.gov.cn/medication/2017",
                        jsonObject.getString("mdDrugCode"),
                        jsonObject.getString("mdDrugName")))
                .addCoding(new Coding("http://www.nhsa.gov.cn/medication/2017",
                        jsonObject.getString("itemCode"),
                        jsonObject.getString("itemName")))
                .setText(jsonObject.getString("drugName")));
        medication.setStatus(Medication.MedicationStatus.ACTIVE);
        //厂家
        medication.setManufacturer(new Reference()
                .setDisplay(jsonObject.getString("manufacturer")));
        //剂型
        medication.setForm(new CodeableConcept()
                .addCoding(new Coding("http://snomed.info/sct",
                        jsonObject.getString("formCode"),
                        jsonObject.getString("formName")))
        );
        //包装规格
        medication.setAmount(new Ratio()
                .setNumerator(new Quantity()
                        .setValue(jsonObject.getDoubleValue("amountNum"))
                        .setUnit(jsonObject.getString("amountNumUnit")))
                .setDenominator(new Quantity()
                        .setValue(jsonObject.getDoubleValue("amountDen"))
                        .setUnit(jsonObject.getString("amountDenUnit")))
        );

        //todo 生成结果没有
        request.addContained(medication);


        //处方项目明细序号
        request.addIdentifier().setSystem("http://xxxxxx.com.cn/org-xxxx/pre-item")
                .setValue(jsonObject.getString("orderNo"));

        //处方状态
        request.setStatus(MedicationRequest.MedicationRequestStatus.ACTIVE);
        request.setIntent(MedicationRequest.MedicationRequestIntent.ORDER);

        //处方分类
        request.addCategory().addCoding()
                .setSystem("http://terminology.hl7.org/CodeSystem/medicationrequest-category")
                .setCode(jsonObject.getString("categoryCode"))
                .setDisplay(jsonObject.getString("categoryName"));
        //药品
        request.setMedication(new Reference()
                .setReference(jsonObject.getString("drugCode"))
                .setDisplay(jsonObject.getString("drugName"))
        );

        //患者
        request.setSubject(new Reference()
                .setDisplay(jsonObject.getString("patientName")));

        //就诊
        request.setEncounter(new Reference());

        //处方 申请信息
        //开立时间
        request.setAuthoredOn(new Date());
        request.setRequester(new Reference().setDisplay(jsonObject.getString("requesterName")));

        //诊断
        request.addReasonCode().addCoding().setSystem("http://snomed.info/sct")
                .setCode(jsonObject.getString("icdCode"))
                .setDisplay(jsonObject.getString("icdName"));
        //处方号
        request.setGroupIdentifier(new Identifier()
                .setSystem("http://xxxxxx.com.cn/org-xxxx/prescription")
                .setValue(jsonObject.getString("groupId")));
        //备注
        request.addNote().setText(jsonObject.getString("note"));

        //用药指导
        request.addDosageInstruction()
                .setTiming(new Timing()
                        .setRepeat(new Timing.TimingRepeatComponent()
                                .setBounds(new Duration()
                                        .setValue(jsonObject.getDoubleValue("days"))
                                        .setUnit("天")
                                ))
                        .setCode(new CodeableConcept()
                                .addCoding(new Coding("http://terminology.hl7.org/CodeSystem/v3-GTSAbbreviation",
                                        jsonObject.getString("frequencyCode"),
                                        jsonObject.getString("frequencyName")
                                )))

                ).setRoute(new CodeableConcept()
                .addCoding(new Coding("http://snomed.info/sct",
                        jsonObject.getString("routeCode"),
                        jsonObject.getString("routeName")
                )))
                .addDoseAndRate(new Dosage.DosageDoseAndRateComponent()
                        .setDose(new Quantity()
                                .setValue(jsonObject.getDoubleValue("dosageQuantity"))
                                .setUnit(jsonObject.getString("dosageUnit"))
                        )
                );
        //发药数量
        request.setDispenseRequest(new MedicationRequest.MedicationRequestDispenseRequestComponent()
                .setQuantity(new Quantity().setValue(jsonObject.getDoubleValue("dispenseQuantity"))
                        .setUnit(jsonObject.getString("dispenseUnit"))
                )
        );

        return request;
    }
}
